package com.zhanghe.study.thread.volatile1;

/**
 * @author zh
 * @date 2023/9/27 22:48
 */
public class TestVolation02 {
    private static boolean initFlag = false;



    public static void main(String[] args) throws InterruptedException {
        Thread thread01 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!initFlag){
                    // 使用Thread.sleep(0)或Thread.yield()就会导致上下文切换，从而使得从主内存load数据
//                    try {
//
//                        Thread.sleep(0);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    Thread.yield();
                }
                System.out.println("thread02开始执行，此时initFlag状态为"+initFlag);
            }
        });

        thread01.start();

        Thread.sleep(1000);
        Thread thread02 = new Thread(new Runnable() {
            @Override
            public void run() {
                initFlag = true;
                System.out.println("thread02修改initFlag状态为"+initFlag);
            }
        });

        thread02.start();

        Thread.sleep(100000);

    }
}
